package nccloud.riart.bs.bgplugin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.am.common.util.CollectionUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nccloud.riart.pub.utils.OAHttpClientUtils;
import nccloud.utils.mobile_riart.MessageLogger;

/**
 * 
 * 定时任务，删除已经被收回的待办任务
 * 
 * @author wangzixu
 *
 */
public class WithdrawPendingTasksPlugins implements IBackgroundWorkPlugin {

	/**
	 * 逻辑控制中心
	 */
	@Override
	public PreAlertObject executeTask(BgWorkingContext context) throws BusinessException {
		nc.bs.logging.Logger.error("WithdrawPending ----- 开始执行删除待办");
		MessageLogger.info("【nccloud.riart.bs.bgplugin.WithdrawPendingTasksPlugins】-------开始执行删除待办");
		// 获取被收回的单据
		List<Map<String, String>> mapList = this.getWithDrawBill();
		if (CollectionUtils.isNotEmpty(mapList)) { 
			try {
				//请求微信token 
				String wxtokenret = OAHttpClientUtils.reqWX_Token();
				JSONObject wxtokenjson = (JSONObject) JSONObject.parse(wxtokenret);
				String wxtoken = wxtokenjson.getString("access_token");
				for (Map<String, String> map : mapList) {
					String oastatus=null;
					String wxjobid =null;
					String message_service = map.get("message_service");
					if(message_service!=null&&message_service.indexOf("#")>0) {
						String [] array = message_service.split("#");
						oastatus = array[0];
						wxjobid = array[1];
					}  
					// 请求OA接口获取返回结果
					String oaresult = null;
					if(oastatus!=null&&!"~".equals(oastatus)) {
						String postData = queryMapToContext(map);
						oaresult = OAHttpClientUtils.reqOA_Task("deleteReceiveUrl", postData);
						nc.bs.logging.Logger.error("请求OA撤回接口返回成功：" + oaresult);
					}
					// 请求WX接口获取返回结果
					String resultWX = null;
					if(wxjobid!=null&&!"~".equals(wxjobid)) {
						String postDataWX = queryMapToContextWX(wxjobid);
						resultWX = OAHttpClientUtils.reqWX_Revoke(postDataWX, wxtoken);
						nc.bs.logging.Logger.error("请求WX撤回接口返回成功：" + resultWX);
					}
					// 同步更新消息状态
					String oares = null;
					if(oaresult!=null) {
						JSONObject retjson = (JSONObject) JSONObject.parse(oaresult);
						oares = retjson.getString("result");
					}else {
						oares="success";
					}
					String wxres = null;
					if(resultWX!=null) {
						JSONObject retjsonwx = (JSONObject) JSONObject.parse(resultWX);
						wxres = retjsonwx.getString("errmsg");
					}else {
						wxres="ok";
					}
					this.synNCCBills(map,oares,wxres);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 获取所有需要删除的待办
	 * 
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, String>> getWithDrawBill() throws BusinessException {
		BaseDAO dao = new BaseDAO(); 
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		// 需要增加时间条件 10分钟内的待办 
		UFDateTime dt = new UFDateTime(System.currentTimeMillis() - 600 * 1000);
		String querySql = "select a.pk_message_user, a.pk_message, a.pk_user,b.message_service from sm_msg_user a "
				+ " left join sm_msg_approve b on a.pk_message=b.pk_message where "
				+ " a.destination = 'inbox' and a.isdelete = 'Y' and nvl(a.dr,0) = 0 and a.message_type = 'approve' "
				+ " and a.ts>'" + dt + "'";
		nc.bs.logging.Logger.error("收回待办sql" + querySql);
		Object coll = dao.executeQuery(querySql, new MapListProcessor());
		if (null != coll) {
			mapList = (ArrayList<Map<String, String>>) coll; 
		}
		return mapList;
	}

	/**
	 * 数据库查询出的数据转为请求的json数据
	 * @param map
	 * @return
	 * @throws Exception
	 */
	private String queryMapToContext(Map<String, String> map) throws Exception {
		String pk_message = map.get("pk_message");
		String urlData = "";
		urlData += "WrkID=" + pk_message;
		return urlData;
		
	}

	/**
	 * 数据库查询出的数据转为请求的json数据
	 * @param wxjobid
	 * @return
	 * @throws Exception
	 */
	private String queryMapToContextWX(String wxjobid) throws Exception {
		String jobid = wxjobid;
		JSONObject jsobj = new JSONObject();
	    jsobj.put("jobid", jobid);//微信消息主键
		return jsobj.toJSONString();
	}

	/**
	 * 删除OA那边的待办消息后，为避免下次继续发送，需要在sm_msg_user 删除
	 * @param map
	 * @param result
	 * @param resultWX
	 * @throws BusinessException
	 */
	private void synNCCBills(Map<String, String> map, String result,String resultWX) throws BusinessException {
		nc.bs.logging.Logger.error("WithdrawPending ----- 执行数据库操作");
		BaseDAO dao = new BaseDAO();
		if (null != map && "success".equals(result) && "ok".equals(resultWX)) {
			if (null != map.get("pk_message_user")) {
				String pk_message_user = map.get("pk_message_user");
				String querySql = " update sm_msg_user set dr='1' where pk_message_user ='" + pk_message_user + "'";
				dao.executeUpdate(querySql);
				nc.bs.logging.Logger.error("WithdrawPending ----- 开始执行更新NCC工作流状态标识");
			}
		}
	}
}
